<template>
  <div class="music-player-container">
    <a-card class="music-player-card" :bordered="false">
      <template #title>
        <div class="page-header">
          <div class="title-section">
            <span class="emoji-title">🎵</span>
            <span class="main-title">音乐播放器</span>
            <span class="emoji-title">🎧</span>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-section">
        <a-input-search
          v-model:value="searchQuery"
          placeholder="输入歌曲名或歌手名搜索"
          enter-button="搜索"
          size="large"
          :loading="searching"
          @search="searchMusic"
          allow-clear
        >
          <template #prefix>
            <search-outlined />
          </template>
        </a-input-search>
      </div>

      <!-- 播放器区域 -->
      <div class="player-section" :class="{ 'active': currentSong }">
        <div class="player-content" v-if="currentSong">
          <div class="album-cover">
            <div class="cover-container" :class="{ 'rotating': isPlaying }">
              <img :src="currentSong.cover" :alt="currentSong.title" class="cover-image" />
            </div>
          </div>

          <div class="song-info">
            <div class="song-title">{{ currentSong.title }}</div>
            <div class="song-artist">{{ currentSong.singer }}</div>

            <div class="progress-bar">
              <div class="time current-time">{{ formatTime(currentTime) }}</div>
              <a-slider
                v-model:value="currentTime"
                :min="0"
                :max="duration || 100"
                :disabled="!currentSong"
                @change="onProgressChange"
                class="progress-slider"
              />
              <div class="time total-time">{{ formatTime(duration) }}</div>
            </div>

            <div class="player-controls">
              <a-button
                type="text"
                shape="circle"
                class="control-btn"
                @click="previousSong"
                :disabled="!hasPreviousSong"
              >
                <template #icon><step-backward-outlined /></template>
              </a-button>

              <a-button
                type="primary"
                shape="circle"
                class="play-btn"
                @click="togglePlay"
                :disabled="!currentSong"
              >
                <template #icon>
                  <pause-outlined v-if="isPlaying" />
                  <caret-right-outlined v-else />
                </template>
              </a-button>

              <a-button
                type="text"
                shape="circle"
                class="control-btn"
                @click="nextSong"
                :disabled="!hasNextSong"
              >
                <template #icon><step-forward-outlined /></template>
              </a-button>
            </div>
          </div>
        </div>

        <div class="empty-player" v-else>
          <play-circle-outlined class="empty-icon" />
          <div class="empty-text">搜索并选择歌曲开始播放</div>
        </div>
      </div>

      <!-- 搜索结果区域 -->
      <div class="search-results" v-if="searchResults.length > 0">
        <div class="section-title">
          <unordered-list-outlined />
          <span>搜索结果</span>
        </div>

        <a-list
          :dataSource="searchResults"
          :loading="searching"
          item-layout="horizontal"
        >
          <template #renderItem="{ item, index }">
            <a-list-item
              class="song-item"
              :class="{ 'active': currentSong && currentSong.index === index }"
              @click="playSong(item, index)"
            >
              <a-list-item-meta>
                <template #avatar>
                  <div class="song-index">{{ index + 1 }}</div>
                </template>
                <template #title>
                  <div class="song-item-title">
                    {{ item.title || '未知歌曲' }}
                    <sound-outlined v-if="currentSong && currentSong.index === index && isPlaying" class="playing-icon" />
                  </div>
                </template>
                <template #description>
                  <div class="song-item-artist">{{ item.singer || '未知歌手' }}</div>
                </template>
              </a-list-item-meta>
              <template #actions>
                <a-button
                  type="text"
                  shape="circle"
                  @click.stop="playSong(item, index)"
                >
                  <template #icon>
                    <pause-outlined v-if="currentSong && currentSong.index === index && isPlaying" />
                    <caret-right-outlined v-else />
                  </template>
                </a-button>
              </template>
            </a-list-item>
          </template>
        </a-list>
      </div>

      <!-- 加载状态 -->
      <div v-if="searching || loading" class="loading-container">
        <a-spin :tip="searching ? '正在搜索音乐...' : '正在加载歌曲...'"></a-spin>
      </div>

      <!-- 错误状态 -->
      <div v-if="error" class="error-container">
        <a-alert
          :message="error"
          type="error"
          show-icon
        />
      </div>

      <!-- 空状态 -->
      <div v-if="searched && searchResults.length === 0 && !searching" class="empty-container">
        <a-empty description="未找到相关音乐">
          <template #description>
            <span>尝试使用其他关键词搜索</span>
          </template>
        </a-empty>
      </div>

      <!-- 音频元素 -->
      <audio
        ref="audioPlayer"
        @timeupdate="onTimeUpdate"
        @loadedmetadata="onLoadedMetadata"
        @ended="onEnded"
        @error="onAudioError"
        :src="currentSong?.music_url"
      ></audio>
    </a-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';
import { message } from 'ant-design-vue';
import axios from 'axios';
import {
  SearchOutlined,
  PlayCircleOutlined,
  CaretRightOutlined,
  PauseOutlined,
  StepBackwardOutlined,
  StepForwardOutlined,
  UnorderedListOutlined,
  SoundOutlined
} from '@ant-design/icons-vue';

// 状态定义
const searchQuery = ref('');
const searchResults = ref([]);
const searching = ref(false);
const loading = ref(false);
const error = ref('');
const searched = ref(false);
const currentSong = ref(null);
const isPlaying = ref(false);
const currentTime = ref(0);
const duration = ref(0);
const audioPlayer = ref(null);
const playHistory = ref([]);

// 计算属性
const hasPreviousSong = computed(() => {
  return playHistory.value.length > 0;
});

const hasNextSong = computed(() => {
  if (!currentSong.value || searchResults.value.length === 0) return false;
  return currentSong.value.index < searchResults.value.length - 1;
});

// 搜索音乐
const searchMusic = async (query) => {
  if (!query.trim()) {
    message.warning('请输入搜索关键词');
    return;
  }

  searching.value = true;
  error.value = '';

  try {
    const response = await axios.get('https://www.hhlqilongzhu.cn/api/dg_mgmusic.php', {
      params: {
        gm: query.trim(),
        n: '' // 空值返回列表
      },
      timeout: 10000
    });

    console.log('搜索响应:', response);

    if (response.data && response.data.code === 200 && Array.isArray(response.data.data)) {
      // 处理搜索结果列表
      searchResults.value = response.data.data;
      searched.value = true;

      if (searchResults.value.length === 0) {
        message.info('未找到相关音乐');
      } else {
        message.success(`找到 ${searchResults.value.length} 首相关音乐`);
      }
    } else {
      error.value = '搜索结果格式错误';
      message.error(error.value);
    }
  } catch (err) {
    console.error('搜索音乐失败:', err);
    error.value = `网络错误: ${err.message}`;
    message.error(error.value);
  } finally {
    searching.value = false;
  }
};

// 播放歌曲
const playSong = async (song, index) => {
  // 如果当前正在播放这首歌，则暂停
  if (currentSong.value && currentSong.value.index === index && isPlaying.value) {
    pauseAudio();
    return;
  }

  // 获取歌曲详情
  loading.value = true;
  error.value = '';

  try {
    const response = await axios.get('https://www.hhlqilongzhu.cn/api/dg_mgmusic.php', {
      params: {
        gm: searchQuery.value.trim(),
        n: song.n // 使用歌曲的n值获取详情
      },
      timeout: 10000
    });

    console.log('歌曲详情响应:', response);

    if (response.data && response.data.code === 200) {
      // 保存当前歌曲到历史记录
      if (currentSong.value) {
        playHistory.value.push({...currentSong.value});
      }

      // 设置新的当前歌曲
      currentSong.value = {
        ...response.data,
        index
      };

      currentTime.value = 0;
      duration.value = 0;

      // 等待下一个事件循环再播放，确保audio元素已更新src
      setTimeout(() => {
        playAudio();
      }, 100);
    } else {
      error.value = '获取歌曲详情失败';
      message.error(error.value);
    }
  } catch (err) {
    console.error('获取歌曲详情失败:', err);
    error.value = `网络错误: ${err.message}`;
    message.error(error.value);
  } finally {
    loading.value = false;
  }
};

// 播放音频
const playAudio = () => {
  if (audioPlayer.value && currentSong.value && currentSong.value.music_url) {
    audioPlayer.value.play()
      .then(() => {
        isPlaying.value = true;
      })
      .catch(err => {
        console.error('播放失败:', err);
        message.error('播放失败，请重试');
        isPlaying.value = false;
      });
  } else {
    message.warning('无法播放，未找到音频链接');
  }
};

// 暂停音频
const pauseAudio = () => {
  if (audioPlayer.value) {
    audioPlayer.value.pause();
    isPlaying.value = false;
  }
};

// 切换播放/暂停
const togglePlay = () => {
  if (isPlaying.value) {
    pauseAudio();
  } else {
    playAudio();
  }
};

// 上一首
const previousSong = () => {
  if (playHistory.value.length > 0) {
    const prevSong = playHistory.value.pop();
    currentSong.value = prevSong;
    currentTime.value = 0;
    duration.value = 0;

    setTimeout(() => {
      playAudio();
    }, 100);
  }
};

// 下一首
const nextSong = () => {
  if (currentSong.value && searchResults.value.length > 0) {
    const nextIndex = currentSong.value.index + 1;
    if (nextIndex < searchResults.value.length) {
      playSong(searchResults.value[nextIndex], nextIndex);
    }
  }
};

// 进度条变化
const onProgressChange = (value) => {
  if (audioPlayer.value) {
    audioPlayer.value.currentTime = value;
  }
};

// 时间更新
const onTimeUpdate = () => {
  if (audioPlayer.value) {
    currentTime.value = Math.floor(audioPlayer.value.currentTime);
  }
};

// 元数据加载完成
const onLoadedMetadata = () => {
  if (audioPlayer.value) {
    duration.value = Math.floor(audioPlayer.value.duration);
  }
};

// 播放结束
const onEnded = () => {
  isPlaying.value = false;

  // 自动播放下一首
  if (hasNextSong.value) {
    nextSong();
  }
};

// 音频错误处理
const onAudioError = (e) => {
  console.error('音频加载错误:', e);
  message.error('音频加载失败，请尝试其他歌曲');
  isPlaying.value = false;
};

// 格式化时间
const formatTime = (seconds) => {
  if (!seconds) return '00:00';

  const mins = Math.floor(seconds / 60);
  const secs = Math.floor(seconds % 60);

  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
};

// 组件卸载时停止播放
onUnmounted(() => {
  if (audioPlayer.value) {
    audioPlayer.value.pause();
  }
});

// 监听搜索框变化，清除错误信息
watch(searchQuery, () => {
  error.value = '';
});
</script>

<style scoped>
.music-player-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.music-player-card {
  border-radius: 16px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  background: linear-gradient(to bottom, #ffffff, #f9f9f9);
}

.page-header {
  text-align: center;
  margin-bottom: 16px;
}

.title-section {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
}

.emoji-title {
  font-size: 2rem;
}

.main-title {
  font-size: 2rem;
  font-weight: bold;
  background: linear-gradient(45deg, #722ed1, #1890ff);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
}

/* 搜索区域 */
.search-section {
  margin-bottom: 24px;
}

/* 播放器区域 */
.player-section {
  margin-bottom: 24px;
  border-radius: 12px;
  overflow: hidden;
  background-color: #f0f2f5;
  transition: all 0.3s ease;
  min-height: 100px;
}

.player-section.active {
  background: linear-gradient(135deg, #722ed1, #1890ff);
  box-shadow: 0 8px 16px rgba(114, 46, 209, 0.2);
}

.player-content {
  display: flex;
  padding: 20px;
  color: white;
}

.album-cover {
  flex-shrink: 0;
  width: 120px;
  height: 120px;
  margin-right: 20px;
}

.cover-container {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  transition: transform 0.3s ease;
}

.cover-container.rotating {
  animation: rotate 20s linear infinite;
}

.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.song-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.song-title {
  font-size: 1.5rem;
  font-weight: bold;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.song-artist {
  font-size: 1rem;
  opacity: 0.8;
  margin-bottom: 16px;
}

.progress-bar {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.time {
  font-size: 0.8rem;
  opacity: 0.8;
  width: 45px;
  text-align: center;
}

.progress-slider {
  flex: 1;
  margin: 0 8px;
}

.player-controls {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16px;
}

.control-btn {
  color: white;
  font-size: 1.2rem;
}

.play-btn {
  width: 48px;
  height: 48px;
  font-size: 1.5rem;
  background: white;
  color: #722ed1;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
}

.empty-player {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100px;
  color: #999;
}

.empty-icon {
  font-size: 2rem;
  margin-bottom: 8px;
}

.empty-text {
  font-size: 1rem;
}

/* 搜索结果区域 */
.search-results {
  margin-bottom: 24px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 1.2rem;
  font-weight: bold;
  margin-bottom: 16px;
  color: #722ed1;
}

.song-item {
  cursor: pointer;
  transition: background-color 0.3s;
  border-radius: 8px;
}

.song-item:hover {
  background-color: #f0f2f5;
}

.song-item.active {
  background-color: #f0f7ff;
}

.song-index {
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f0f2f5;
  color: #666;
  border-radius: 50%;
  font-weight: bold;
}

.song-item.active .song-index {
  background-color: #722ed1;
  color: white;
}

.song-item-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.playing-icon {
  color: #722ed1;
  animation: pulse 1s infinite;
}

.song-item-artist {
  color: #666;
}

/* 加载和错误状态 */
.loading-container, .error-container, .empty-container {
  padding: 20px 0;
  text-align: center;
}

/* 动画 */
@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

@keyframes pulse {
  0% { opacity: 0.5; }
  50% { opacity: 1; }
  100% { opacity: 0.5; }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .music-player-container {
    padding: 10px;
  }

  .main-title {
    font-size: 1.5rem;
  }

  .emoji-title {
    font-size: 1.5rem;
  }

  .player-content {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }

  .album-cover {
    margin-right: 0;
    margin-bottom: 20px;
  }

  .song-title {
    white-space: normal;
    overflow: visible;
  }
}
</style>
